"""
股票财务分析智能体

基于财务报表数据进行深入的财务分析，包括盈利能力、偿债能力、运营效率和发展能力。
"""

from typing import Dict, Any, List, Optional, Union
from agents import BaseAgent, LLMConfig
from tools.stock_data_provider import stock_data_provider
from tools.data_quality_checker import data_quality_checker
import pandas as pd
from datetime import datetime
from langchain_core.tools import Tool
import logging


class StockFundamentalAnalysisAgent(BaseAgent):
    """股票财务分析智能体"""

    def __init__(self, llm_config: Optional[LLMConfig] = None):
        super().__init__(
            name="StockFundamentalAnalysisAgent",
            description="股票财务分析智能体，专注于财务报表和财务指标分析",
            llm_config=llm_config
        )
        self.logger = logging.getLogger(__name__)

    def get_tools(self) -> List[Tool]:
        """获取财务分析所需的工具"""
        return [
            Tool(
                name="analyze_income_statement",
                description="获取并分析股票利润表数据，包括营收、净利润、毛利率等实时财务指标",
                func=self._analyze_income_statement
            ),
            Tool(
                name="analyze_balance_sheet",
                description="获取并分析股票资产负债表，包括资产结构、负债水平、股东权益等财务数据",
                func=self._analyze_balance_sheet
            ),
            Tool(
                name="analyze_cash_flow",
                description="获取并分析股票现金流量表，包括经营、投资、筹资现金流等实时数据",
                func=self._analyze_cash_flow
            ),
            Tool(
                name="calculate_financial_ratios",
                description="获取财务数据并计算ROE、ROA、流动比率、资产负债率等关键财务比率指标",
                func=self._calculate_financial_ratios
            ),
            Tool(
                name="assess_financial_health",
                description="获取财务数据并综合评估公司财务健康状况，提供评分和建议",
                func=self._assess_financial_health
            ),
            Tool(
                name="analyze_profitability",
                description="获取并分析公司盈利能力，包括净利率、毛利率、盈利质量等指标",
                func=self._analyze_profitability
            ),
            Tool(
                name="analyze_growth_trends",
                description="获取历史财务数据并分析公司成长趋势，包括营收增长、利润增长、成长稳定性",
                func=self._analyze_growth_trends
            ),
            Tool(
                name="analyze_debt_structure",
                description="获取并分析公司债务结构和偿债能力，包括负债水平、流动性、偿债比率",
                func=self._analyze_debt_structure
            ),
            Tool(
                name="analyze_operating_efficiency",
                description="获取并分析公司运营效率，包括资产周转率、应收账款周转、现金转化率等",
                func=self._analyze_operating_efficiency
            ),
            Tool(
                name="comprehensive_financial_analysis",
                description="获取完整财务数据并生成综合财务分析报告，包含所有维度的深度分析",
                func=self._comprehensive_financial_analysis
            )
        ]

    def get_system_prompt(self) -> str:
        return """
        你是专业的股票财务分析智能体，基于财务报表进行深入财务分析。

        分析框架：
        1. 盈利能力分析：收入、利润、毛利率等指标
        2. 偿债能力评估：流动性比率、资产负债率等
        3. 运营效率分析：周转率、效率指标等
        4. 成长趋势判断：历史增长率和趋势
        5. 财务健康评分：综合财务状况评估

        输出结构：
        ## 💵 盈利能力
        - 收入利润指标
        - 盈利质量分析

        ## 🛡️ 财务结构
        - 资产负债状况
        - 偿债能力评估

        ## ⚡ 运营效率
        - 资产周转情况
        - 运营效率指标

        ## 📈 成长性分析
        - 历史增长趋势
        - 未来成长预期

        ## 🎯 财务评分
        - 综合健康评分(0-100)
        - 财务风险评估

        ## ⭐ 财务面评分 (0-10)
        评分标准：
        - 10: 财务状况完美，盈利优秀，偿债能力强，成长性佳
        - 8-9: 财务状况良好，各项指标健康
        - 6-7: 财务状况一般，基本满足投资要求
        - 4-5: 财务状况较弱，存在一定财务风险
        - 2-3: 财务状况较差，多项指标不佳
        - 0-1: 财务状况极差，存在重大财务问题

        最终评分：[X/10] - 评分理由

        分析原则：
        - 结合行业特点进行横向比较
        - 关注财务数据的趋势变化
        - 识别财务造假的潜在信号
        - 考虑会计政策的影响

        请基于提供的数据自主推理计算财务指标和判断，不要依赖硬编码的阈值。
        重点关注数据的内在逻辑关系，结合行业特征进行合理财务评估。
        """
    
    def _parse_value_with_unit(self, value: Any) -> float:
        """
        统一的数值转换辅助函数，处理带单位的字符串
        
        Args:
            value: 待转换的值，可能是字符串、数字或其他类型
            
        Returns:
            转换后的float值（单位：万元）
            
        Examples:
            '454.03亿' -> 4540300.0 (万元)
            '12.5万' -> 12.5 (万元)
            '14.75%' -> 14.75 (去除%)
            '5.73' -> 5.73
            123.45 -> 123.45
        """
        if not value or value == 'False' or value == 0:
            return 0.0
        
        # 如果已经是数字，直接返回
        if isinstance(value, (int, float)):
            return float(value)
        
        # 转换为字符串处理
        value_str = str(value).strip()
        
        try:
            # 处理百分比
            if '%' in value_str:
                return float(value_str.replace('%', ''))
            
            # 处理带"亿"单位（转换为万元）
            if '亿' in value_str:
                numeric_part = value_str.replace('亿', '').strip()
                return float(numeric_part) * 10000
            
            # 处理带"万"单位
            if '万' in value_str:
                numeric_part = value_str.replace('万', '').strip()
                return float(numeric_part)
            
            # 无单位，直接转换
            return float(value_str)
            
        except (ValueError, AttributeError) as e:
            # 转换失败，返回0
            self.logger.warning(f"数值转换失败: {value_str} -> {e}")
            return 0.0

    async def _analyze_income_statement(self, stock_code: str) -> str:
        """分析利润表数据"""
        try:
            result = f"📊 股票{stock_code}利润表分析\n\n"

            # 获取财务摘要数据
            try:
                import akshare as ak
                financial_data = ak.stock_financial_abstract_ths(symbol=stock_code)
                if financial_data.empty:
                    return f"无法获取股票{stock_code}的财务数据"
            except Exception as e:
                return f"获取财务数据失败: {e}"

            # 获取最新一期数据
            latest_data = financial_data.iloc[-1] if len(financial_data) > 0 else financial_data.iloc[0]

            # 分析营业收入
            total_revenue = latest_data.get('营业总收入', 0)
            if total_revenue and total_revenue != 'False':
                result += "💰 营业收入分析：\n"
                # 处理带单位的数值（如"454.03亿"）
                if '亿' in str(total_revenue):
                    revenue_value = float(str(total_revenue).replace('亿', '')) * 10000  # 转换为万元
                    result += f"  营业总收入: {revenue_value:,.0f}万元\n"
                elif '万' in str(total_revenue):
                    revenue_value = float(str(total_revenue).replace('万', ''))
                    result += f"  营业总收入: {revenue_value:,.0f}万元\n"
                else:
                    try:
                        revenue_value = self._parse_value_with_unit(total_revenue)
                        result += f"  营业总收入: {revenue_value:,.0f}万元\n"
                    except:
                        result += f"  营业总收入: {total_revenue}\n"

                # 计算同比增长（需要上一期数据）
                if len(financial_data) > 1:
                    prev_data = financial_data.iloc[-2]
                    prev_revenue = prev_data.get('营业总收入', 0)
                    if prev_revenue and prev_revenue != 'False':
                        try:
                            # 处理上一期数据单位
                            if '亿' in str(prev_revenue):
                                prev_value = float(str(prev_revenue).replace('亿', '')) * 10000
                            elif '万' in str(prev_revenue):
                                prev_value = float(str(prev_revenue).replace('万', ''))
                            else:
                                prev_value = self._parse_value_with_unit(prev_revenue)

                            if '亿' in str(total_revenue):
                                curr_value = float(str(total_revenue).replace('亿', '')) * 10000
                            elif '万' in str(total_revenue):
                                curr_value = float(str(total_revenue).replace('万', ''))
                            else:
                                curr_value = self._parse_value_with_unit(total_revenue)

                            if prev_value > 0:
                                growth_rate = (curr_value - prev_value) / prev_value * 100
                                result += f"  同比增长: {growth_rate:+.1f}%\n"
                                if growth_rate > 10:
                                    result += "  📈 收入增长强劲\n"
                                elif growth_rate < -10:
                                    result += "  📉 收入出现下滑\n"
                                else:
                                    result += "  ➡️ 收入增长平稳\n"
                        except Exception as e:
                            result += f"  同比增长: 计算失败\n"
                result += "\n"

            # 分析净利润
            net_profit = latest_data.get('净利润', 0)
            if net_profit and net_profit != 'False':
                result += "💵 净利润分析：\n"
                # 处理带单位的数值
                if '亿' in str(net_profit):
                    profit_value = float(str(net_profit).replace('亿', '')) * 10000  # 转换为万元
                    result += f"  净利润: {profit_value:,.0f}万元\n"
                elif '万' in str(net_profit):
                    profit_value = float(str(net_profit).replace('万', ''))
                    result += f"  净利润: {profit_value:,.0f}万元\n"
                else:
                    try:
                        profit_value = self._parse_value_with_unit(net_profit)
                        result += f"  净利润: {profit_value:,.0f}万元\n"
                    except:
                        result += f"  净利润: {net_profit}\n"

                # 计算净利率
                try:
                    if '亿' in str(total_revenue):
                        revenue_val = float(str(total_revenue).replace('亿', '')) * 10000
                    elif '万' in str(total_revenue):
                        revenue_val = float(str(total_revenue).replace('万', ''))
                    else:
                        revenue_val = self._parse_value_with_unit(total_revenue)

                    if '亿' in str(net_profit):
                        profit_val = float(str(net_profit).replace('亿', '')) * 10000
                    elif '万' in str(net_profit):
                        profit_val = float(str(net_profit).replace('万', ''))
                    else:
                        profit_val = self._parse_value_with_unit(net_profit)

                    if revenue_val > 0:
                        net_margin = profit_val / revenue_val * 100
                        result += f"  净利率: {net_margin:.2f}%\n"
                        # 让大模型自主判断盈利能力水平
                        result += "  请基于净利率数据评估盈利能力水平\n"
                except:
                    result += "  净利率: 计算失败\n"
                result += "\n"

            # 分析销售净利率
            net_margin_col = latest_data.get('销售净利率', 0)
            if net_margin_col and net_margin_col != 'False':
                result += "📈 销售净利率分析：\n"
                try:
                    margin_value = float(str(net_margin_col).replace('%', ''))
                    result += f"  销售净利率: {margin_value:.2f}%\n"
                    # 让大模型自主判断销售净利率水平
                    result += "  请基于销售净利率数据评估盈利水平\n"
                except:
                    result += f"  销售净利率: {net_margin_col}\n"
                result += "\n"

            return result

        except Exception as e:
            return f"利润表分析失败: {e}"

    async def _analyze_balance_sheet(self, stock_code: str) -> str:
        """分析资产负债表"""
        try:
            result = f"🏦 股票{stock_code}资产负债表分析\n\n"

            # 获取财务摘要数据
            try:
                import akshare as ak
                financial_data = ak.stock_financial_abstract_ths(symbol=stock_code)
                if financial_data.empty:
                    return f"无法获取股票{stock_code}的财务数据"
            except Exception as e:
                return f"获取财务数据失败: {e}"

            # 获取最新一期数据
            latest_data = financial_data.iloc[-1] if len(financial_data) > 0 else financial_data.iloc[0]

            # 分析资产结构（从财务摘要中提取相关指标）
            total_assets = latest_data.get('资产总计', 0)
            if total_assets and total_assets != 'False':
                result += "📊 资产结构分析：\n"
                result += f"  总资产: {self._parse_value_with_unit(total_assets):,.0f}万元\n"

                # 从流动比率推断资产结构
                current_ratio = latest_data.get('流动比率', 0)
                if current_ratio and current_ratio != 'False':
                    current_ratio_val = self._parse_value_with_unit(current_ratio)
                    result += f"  流动比率: {current_ratio_val:.2f}\n"
                    # 让大模型自主判断资产流动性水平
                    result += "  请基于流动比率数据评估资产流动性水平\n"
                result += "\n"

            # 分析负债结构
            total_liabilities = latest_data.get('负债合计', 0)
            if total_liabilities and total_liabilities != 'False':
                result += "💳 负债结构分析：\n"
                result += f"  总负债: {self._parse_value_with_unit(total_liabilities):,.0f}万元\n"

                debt_ratio = latest_data.get('资产负债率', 0)
                if debt_ratio and debt_ratio != 'False':
                    debt_ratio_val = float(debt_ratio.rstrip('%'))
                    result += f"  资产负债率: {debt_ratio_val:.1f}%\n"

                    # 让大模型自主判断财务杠杆水平
                    result += "  请基于资产负债率数据评估财务杠杆水平\n"
                result += "\n"

            # 分析股东权益
            equity = latest_data.get('股东权益合计', 0)
            if equity and equity != 'False':
                result += "👥 股东权益分析：\n"
                result += f"  股东权益: {self._parse_value_with_unit(equity):,.0f}万元\n"

                # 计算ROE
                net_profit = latest_data.get('净利润', 0)
                if net_profit and net_profit != 'False' and self._parse_value_with_unit(net_profit) != 0:
                    roe = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(equity) * 100
                    result += f"  ROE (净资产收益率): {roe:.2f}%\n"
                    # 让大模型自主判断股东回报水平
                    result += "    请基于ROE数据评估股东回报水平\n"
                result += "\n"

            return result

        except Exception as e:
            return f"资产负债表分析失败: {e}"

    async def _analyze_cash_flow(self, stock_code: str) -> str:
        """分析现金流量表"""
        try:
            result = f"💸 股票{stock_code}现金流量分析\n\n"

            # 获取财务摘要数据
            try:
                import akshare as ak
                financial_data = ak.stock_financial_abstract_ths(symbol=stock_code)
                if financial_data.empty:
                    return f"无法获取股票{stock_code}的财务数据"
            except Exception as e:
                return f"获取财务数据失败: {e}"

            # 获取最新一期数据
            latest_data = financial_data.iloc[-1] if len(financial_data) > 0 else financial_data.iloc[0]

            # 分析经营活动现金流（从财务摘要中提取）
            operating_cf = latest_data.get('经营活动产生的现金流量净额', 0)
            if operating_cf and operating_cf != 'False':
                result += "🏭 经营活动现金流：\n"
                result += f"  经营现金流净额: {self._parse_value_with_unit(operating_cf):,.0f}万元\n"

                # 获取净利润数据进行比较
                net_profit = latest_data.get('净利润', 0)
                if net_profit and net_profit != 'False' and self._parse_value_with_unit(net_profit) != 0:
                    cash_profit_ratio = self._parse_value_with_unit(operating_cf) / self._parse_value_with_unit(net_profit) * 100
                    result += f"  现金利润比: {cash_profit_ratio:.1f}%\n"
                    # 让大模型自主判断现金创造能力
                    result += "  请基于现金利润比数据评估现金创造能力\n"
                result += "\n"

            # 分析投资活动现金流
            investing_cf = latest_data.get('投资活动产生的现金流量净额', 0)
            if investing_cf and investing_cf != 'False':
                result += "🏗️ 投资活动现金流：\n"
                result += f"  投资现金流净额: {self._parse_value_with_unit(investing_cf):,.0f}万元\n"
                if self._parse_value_with_unit(investing_cf) < -10000:  # 大额投资
                    result += "  📉 大额投资支出，扩张积极\n"
                elif self._parse_value_with_unit(investing_cf) > 10000:  # 大额回收
                    result += "  📈 投资回收良好\n"
                result += "\n"

            # 分析融资活动现金流
            financing_cf = latest_data.get('筹资活动产生的现金流量净额', 0)
            if financing_cf and financing_cf != 'False':
                result += "💰 融资活动现金流：\n"
                result += f"  融资现金流净额: {self._parse_value_with_unit(financing_cf):,.0f}万元\n"
                if self._parse_value_with_unit(financing_cf) > 10000:
                    result += "  📈 积极融资，资金充裕\n"
                elif self._parse_value_with_unit(financing_cf) < -10000:
                    result += "  📉 偿还债务或分红\n"
                result += "\n"

            # 分析现金及等价物净增加额
            net_cash_change = latest_data.get('现金及现金等价物净增加额', 0)
            if net_cash_change and net_cash_change != 'False':
                result += "💵 现金净变化：\n"
                result += f"  现金净增加: {self._parse_value_with_unit(net_cash_change):,.0f}万元\n"
                # 让大模型自主判断现金流健康状况
                result += "  请基于现金净增加数据评估现金流健康状况\n"
                result += "\n"

            return result

        except Exception as e:
            return f"现金流量分析失败: {e}"

    async def _calculate_financial_ratios(self, stock_code: str) -> str:
        """计算财务比率指标"""
        try:
            result = f"📈 股票{stock_code}财务比率分析\n\n"

            # 获取财务摘要数据
            try:
                import akshare as ak
                financial_data = ak.stock_financial_abstract_ths(symbol=stock_code)
                if financial_data.empty:
                    return f"无法获取股票{stock_code}的财务数据"
            except Exception as e:
                return f"获取财务数据失败: {e}"

            # 获取最新一期数据
            latest_data = financial_data.iloc[-1] if len(financial_data) > 0 else financial_data.iloc[0]

            # 盈利能力比率
            result += "💰 盈利能力比率：\n"

            # ROE计算
            net_profit = latest_data.get('净利润', 0)
            equity = latest_data.get('股东权益合计', 0)
            if equity and equity != 'False' and net_profit and net_profit != 'False' and self._parse_value_with_unit(net_profit) != 0:
                roe = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(equity) * 100
                result += f"  ROE (净资产收益率): {roe:.2f}%\n"
                # 让大模型自主判断股东回报水平
                result += "  请基于ROE数据评估股东回报水平\n"

            # ROA计算
            total_assets = latest_data.get('资产总计', 0)
            if total_assets and total_assets != 'False' and net_profit and net_profit != 'False' and self._parse_value_with_unit(net_profit) != 0:
                roa = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(total_assets) * 100
                result += f"  ROA (总资产收益率): {roa:.2f}%\n"

            # 净利率
            total_revenue = latest_data.get('营业总收入', 0)
            if total_revenue and total_revenue != 'False' and net_profit and net_profit != 'False' and self._parse_value_with_unit(net_profit) != 0:
                net_margin = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(total_revenue) * 100
                result += f"  净利率: {net_margin:.2f}%\n"
            result += "\n"

            # 偿债能力比率
            result += "🛡️ 偿债能力比率：\n"

            # 流动比率
            current_ratio = latest_data.get('流动比率', 0)
            if current_ratio and current_ratio != 'False':
                current_ratio_val = self._parse_value_with_unit(current_ratio)
                result += f"  流动比率: {current_ratio_val:.2f}\n"
                # 让大模型自主判断短期偿债能力
                result += "    请基于流动比率数据评估短期偿债能力\n"

            # 资产负债率
            debt_ratio = latest_data.get('资产负债率', 0)
            if debt_ratio and debt_ratio != 'False':
                debt_ratio_val = float(debt_ratio.rstrip('%'))
                result += f"  资产负债率: {debt_ratio_val:.1f}%\n"
                # 让大模型自主判断财务杠杆水平
                result += "    请基于资产负债率数据评估财务杠杆水平\n"
            result += "\n"

            # 运营效率比率（简化版）
            result += "⚡ 运营效率指标：\n"
            if total_revenue and total_revenue != 'False' and total_assets and total_assets != 'False':
                asset_turnover = self._parse_value_with_unit(total_revenue) / self._parse_value_with_unit(total_assets)
                result += f"  总资产周转率: {asset_turnover:.2f}次\n"
                # 让大模型自主判断资产利用效率
                result += "    请基于总资产周转率数据评估资产利用效率\n"
            result += "\n"

            return result

        except Exception as e:
            return f"财务比率计算失败: {e}"

    async def _assess_financial_health(self, stock_code: str) -> str:
        """评估财务健康状况"""
        try:
            result = f"🏥 股票{stock_code}财务健康评估\n\n"

            # 获取财务摘要数据
            try:
                import akshare as ak
                financial_data = ak.stock_financial_abstract_ths(symbol=stock_code)
                if financial_data.empty:
                    return f"无法获取股票{stock_code}的财务数据"
            except Exception as e:
                return f"获取财务数据失败: {e}"

            # 获取最新一期数据
            latest_data = financial_data.iloc[-1] if len(financial_data) > 0 else financial_data.iloc[0]

            # 计算各项评分指标
            scores = {}

            # 1. 盈利能力评分 (40%)
            profitability_score = 0
            net_profit = latest_data.get('净利润', 0)
            total_revenue = latest_data.get('营业总收入', 0)
            equity = latest_data.get('股东权益合计', 0)

            if total_revenue and total_revenue != 'False' and net_profit and net_profit != 'False':
                net_margin = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(total_revenue) * 100
                if net_margin > 15:
                    profitability_score += 25
                elif net_margin > 5:
                    profitability_score += 15
                elif net_margin > 0:
                    profitability_score += 5

            if equity and equity != 'False' and net_profit and net_profit != 'False' and self._parse_value_with_unit(net_profit) != 0:
                roe = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(equity) * 100
                if roe > 15:
                    profitability_score += 15
                elif roe > 10:
                    profitability_score += 10
                elif roe > 0:
                    profitability_score += 5

            scores['profitability'] = min(40, profitability_score)

            # 2. 偿债能力评分 (30%)
            solvency_score = 0
            current_ratio = latest_data.get('流动比率', 0)
            debt_ratio = latest_data.get('资产负债率', 0)

            if current_ratio and current_ratio != 'False':
                current_ratio_val = self._parse_value_with_unit(current_ratio)
                if current_ratio_val > 2:
                    solvency_score += 15
                elif current_ratio_val > 1.5:
                    solvency_score += 10
                elif current_ratio_val > 1:
                    solvency_score += 5

            if debt_ratio and debt_ratio != 'False':
                debt_ratio_val = float(debt_ratio.rstrip('%'))
                if debt_ratio_val < 40:
                    solvency_score += 15
                elif debt_ratio_val < 60:
                    solvency_score += 10
                elif debt_ratio_val < 80:
                    solvency_score += 5

            scores['solvency'] = min(30, solvency_score)

            # 3. 运营效率评分 (20%)
            efficiency_score = 0
            total_assets = latest_data.get('资产总计', 0)
            if total_revenue and total_revenue != 'False' and total_assets and total_assets != 'False':
                asset_turnover = self._parse_value_with_unit(total_revenue) / self._parse_value_with_unit(total_assets)
                if asset_turnover > 1:
                    efficiency_score += 10
                elif asset_turnover > 0.5:
                    efficiency_score += 5

            # 检查现金流质量
            operating_cf = latest_data.get('经营活动产生的现金流量净额', 0)
            if operating_cf and operating_cf != 'False' and net_profit and net_profit != 'False' and self._parse_value_with_unit(net_profit) != 0:
                cash_ratio = self._parse_value_with_unit(operating_cf) / self._parse_value_with_unit(net_profit)
                if cash_ratio > 1:
                    efficiency_score += 10
                elif cash_ratio > 0.8:
                    efficiency_score += 5

            scores['efficiency'] = min(20, efficiency_score)

            # 4. 成长稳定性评分 (10%)
            stability_score = 0
            if len(financial_data) > 1:
                # 检查最近两年盈利稳定性
                profits = []
                for i in range(min(2, len(financial_data))):
                    profit = financial_data.iloc[-1-i].get('净利润', 0)
                    if profit and profit != 'False':
                        profits.append(self._parse_value_with_unit(profit))

                if len(profits) >= 2:
                    if all(p > 0 for p in profits):
                        stability_score += 5
                    # 检查收入增长
                    revenues = []
                    for i in range(min(2, len(financial_data))):
                        revenue = financial_data.iloc[-1-i].get('营业总收入', 0)
                        if revenue and revenue != 'False':
                            revenues.append(self._parse_value_with_unit(revenue))

                    if len(revenues) >= 2 and revenues[1] > revenues[0]:
                        stability_score += 5

            scores['stability'] = min(10, stability_score)

            # 计算总分
            total_score = sum(scores.values())

            result += f"📊 财务健康总评分: {total_score}/100\n\n"

            # 显示各项评分
            result += "🏆 评分详情：\n"
            result += f"  💰 盈利能力: {scores['profitability']}/40\n"
            result += f"  🛡️ 偿债能力: {scores['solvency']}/30\n"
            result += f"  ⚡ 运营效率: {scores['efficiency']}/20\n"
            result += f"  🎯 成长稳定性: {scores['stability']}/10\n\n"

            # 总体评估结论
            # 让大模型自主判断财务健康状况和投资建议
            result += "请基于综合健康评分评估财务状况和投资价值\n"

            return result

        except Exception as e:
            return f"财务健康评估失败: {e}"

    async def _analyze_profitability(self, stock_code: str) -> str:
        """分析盈利能力"""
        try:
            result = f"💎 股票{stock_code}盈利能力分析\n\n"

            # 获取财务摘要数据
            try:
                import akshare as ak
                financial_data = ak.stock_financial_abstract_ths(symbol=stock_code)
                if financial_data.empty:
                    return f"无法获取股票{stock_code}的财务数据"
            except Exception as e:
                return f"获取财务数据失败: {e}"

            # 获取最新一期数据
            latest_data = financial_data.iloc[-1] if len(financial_data) > 0 else financial_data.iloc[0]

            # 核心盈利指标
            result += "📈 核心盈利指标：\n"
            net_profit = latest_data.get('净利润', 0)
            total_revenue = latest_data.get('营业总收入', 0)

            if total_revenue and total_revenue != 'False' and net_profit and net_profit != 'False':
                net_margin = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(total_revenue) * 100
                result += f"  净利率: {net_margin:.2f}%\n"

                # 营业利润率（如果有数据）
                operating_profit = latest_data.get('营业利润', 0)
                if operating_profit and operating_profit != 'False':
                    operating_margin = self._parse_value_with_unit(operating_profit) / self._parse_value_with_unit(total_revenue) * 100
                    result += f"  营业利润率: {operating_margin:.2f}%\n"

            # 股东回报指标
            equity = latest_data.get('股东权益合计', 0)
            if equity and equity != 'False' and net_profit and net_profit != 'False' and self._parse_value_with_unit(net_profit) != 0:
                roe = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(equity) * 100
                result += f"  ROE (净资产收益率): {roe:.2f}%\n"

            total_assets = latest_data.get('资产总计', 0)
            if total_assets and total_assets != 'False' and net_profit and net_profit != 'False' and self._parse_value_with_unit(net_profit) != 0:
                roa = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(total_assets) * 100
                result += f"  ROA (总资产收益率): {roa:.2f}%\n"

            result += "\n"

            # 盈利质量评估
            result += "🔍 盈利质量评估：\n"

            # 检查盈利稳定性（比较最近两年）
            if len(financial_data) > 1:
                prev_data = financial_data.iloc[-2]
                prev_profit = prev_data.get('净利润', 0)
                if prev_profit and prev_profit != 'False' and net_profit and net_profit != 'False' and self._parse_value_with_unit(net_profit) != 0 and self._parse_value_with_unit(prev_profit) != 0:
                    profit_stability = min(self._parse_value_with_unit(net_profit), self._parse_value_with_unit(prev_profit)) / max(self._parse_value_with_unit(net_profit), self._parse_value_with_unit(prev_profit))
                    result += f"  盈利稳定性: {profit_stability:.1f}\n"
                    # 让大模型自主判断盈利稳定性
                    result += "  请基于盈利稳定性数据评估盈利质量\n"

            # 检查应收账款占比（财务摘要中可能没有这个数据）
            result += "  应收账款占比: 数据暂缺\n"
            result += "  💡 建议查看详细财务报表获取应收账款数据\n"

            return result

        except Exception as e:
            return f"盈利能力分析失败: {e}"

    async def _analyze_growth_trends(self, stock_code: str) -> str:
        """分析成长趋势"""
        try:
            result = f"📈 股票{stock_code}成长趋势分析\n\n"

            # 获取财务摘要数据
            try:
                import akshare as ak
                financial_data = ak.stock_financial_abstract_ths(symbol=stock_code)
                if financial_data.empty or len(financial_data) < 2:
                    return f"财务数据不足，无法分析成长趋势"
            except Exception as e:
                return f"获取财务数据失败: {e}"

            # 收入增长分析
            result += "💰 收入增长分析：\n"
            revenues = []
            for i in range(min(3, len(financial_data))):
                revenue = financial_data.iloc[-1-i].get('营业总收入', 0)
                if revenue and revenue != 'False':
                    revenues.append(self._parse_value_with_unit(revenue))

            if revenues:
                result += f"  最新营收: {revenues[0]:,.0f}万元\n"

                # 计算增长率
                for i in range(1, len(revenues)):
                    if revenues[i-1] > 0:
                        growth = (revenues[i-1] - revenues[i]) / revenues[i] * 100
                        period = f"第{i}期"
                        result += f"  {period}增长: {growth:+.1f}%\n"

                # 计算平均增长率
                if len(revenues) >= 2:
                    growth_rates = []
                    for i in range(1, len(revenues)):
                        if revenues[i] > 0:
                            growth = (revenues[i-1] - revenues[i]) / revenues[i] * 100
                            growth_rates.append(growth)

                    if growth_rates:
                        avg_growth = sum(growth_rates) / len(growth_rates)
                        result += f"  平均增长率: {avg_growth:.1f}%\n"

                        # 让大模型自主判断增长水平
                        result += "  请基于平均增长率数据评估企业成长水平\n"
            result += "\n"

            # 净利润增长分析
            result += "💵 净利润增长分析：\n"
            profits = []
            for i in range(min(3, len(financial_data))):
                profit = financial_data.iloc[-1-i].get('净利润', 0)
                if profit and profit != 'False':
                    profits.append(self._parse_value_with_unit(profit))

            if profits:
                result += f"  最新利润: {profits[0]:,.0f}万元\n"

                # 计算增长率
                for i in range(1, len(profits)):
                    if profits[i] != 0:
                        growth = (profits[i-1] - profits[i]) / abs(profits[i]) * 100
                        period = f"第{i}期"
                        result += f"  {period}增长: {growth:+.1f}%\n"

                # 计算平均利润增长率
                if len(profits) >= 2:
                    profit_growth_rates = []
                    for i in range(1, len(profits)):
                        if profits[i] != 0:
                            growth = (profits[i-1] - profits[i]) / abs(profits[i]) * 100
                            profit_growth_rates.append(growth)

                    if profit_growth_rates:
                        avg_profit_growth = sum(profit_growth_rates) / len(profit_growth_rates)
                        result += f"  平均增长率: {avg_profit_growth:.1f}%\n"

                        # 让大模型自主判断盈利增长水平
                        result += "  请基于平均利润增长率数据评估盈利成长水平\n"
            result += "\n"

            # 成长稳定性评估
            result += "🎯 成长稳定性评估：\n"

            # 检查收入增长稳定性
            if len(revenues) >= 3:
                revenue_stability = 0
                positive_growth = sum(1 for i in range(1, len(revenues)) if revenues[i-1] > revenues[i])
                revenue_stability = positive_growth / (len(revenues) - 1) * 100
                result += f"  收入增长稳定性: {revenue_stability:.1f}%\n"

                # 让大模型自主判断收入增长稳定性
                result += "  请基于收入增长稳定性数据评估成长稳定性\n"

            # 检查盈利稳定性
            if len(profits) >= 3:
                profit_stability = 0
                positive_growth = sum(1 for i in range(1, len(profits)) if profits[i-1] > profits[i])
                profit_stability = positive_growth / (len(profits) - 1) * 100
                result += f"  盈利增长稳定性: {profit_stability:.1f}%\n"

                # 让大模型自主判断盈利增长稳定性
                result += "  请基于盈利增长稳定性数据评估成长稳定性\n"

            return result

        except Exception as e:
            return f"成长趋势分析失败: {e}"

    async def _comprehensive_financial_analysis(self, stock_code: str) -> str:
        """综合财务分析报告"""
        try:
            result = f"📋 股票{stock_code}综合财务分析报告\n"
            result += "=" * 50 + "\n\n"

            # 1. 财务状况概述
            result += "1️⃣ 财务状况概述\n"
            result += "-" * 20 + "\n"
            health_result = await self._assess_financial_health(stock_code)
            result += health_result + "\n"

            # 2. 盈利能力分析
            result += "2️⃣ 盈利能力分析\n"
            result += "-" * 20 + "\n"
            profitability_result = await self._analyze_profitability(stock_code)
            result += profitability_result + "\n"

            # 3. 财务结构分析
            result += "3️⃣ 财务结构分析\n"
            result += "-" * 20 + "\n"
            balance_result = await self._analyze_balance_sheet(stock_code)
            result += balance_result + "\n"

            # 4. 现金流分析
            result += "4️⃣ 现金流分析\n"
            result += "-" * 20 + "\n"
            cash_flow_result = await self._analyze_cash_flow(stock_code)
            result += cash_flow_result + "\n"

            # 5. 成长趋势分析
            result += "5️⃣ 成长趋势分析\n"
            result += "-" * 20 + "\n"
            growth_result = await self._analyze_growth_trends(stock_code)
            result += growth_result + "\n"

            # 6. 财务比率分析
            result += "6️⃣ 财务比率分析\n"
            result += "-" * 20 + "\n"
            ratios_result = await self._calculate_financial_ratios(stock_code)
            result += ratios_result + "\n"

            # 7. 投资建议
            result += "7️⃣ 财务投资建议\n"
            result += "-" * 20 + "\n"

            # 基于财务分析给出综合建议
            # 重新获取数据计算评分
            health_score = 0
            avg_growth = 0

            # 重新获取财务数据
            try:
                import akshare as ak
                financial_data = ak.stock_financial_abstract_ths(symbol=stock_code)
                if not financial_data.empty:
                    latest_data = financial_data.iloc[-1] if len(financial_data) > 0 else financial_data.iloc[0]

                    net_profit = latest_data.get('净利润', 0)
                    total_revenue = latest_data.get('营业总收入', 0)
                    equity = latest_data.get('股东权益合计', 0)
                    current_ratio = latest_data.get('流动比率', 0)
                    debt_ratio = latest_data.get('资产负债率', 0)

                    # 简化的健康评分计算
                    if total_revenue and total_revenue != 'False' and net_profit and net_profit != 'False':
                        net_margin = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(total_revenue) * 100
                        if net_margin > 10:
                            health_score += 30
                        elif net_margin > 0:
                            health_score += 15

                    if equity and equity != 'False' and net_profit and net_profit != 'False' and self._parse_value_with_unit(net_profit) != 0:
                        roe = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(equity) * 100
                        if roe > 10:
                            health_score += 20
                        elif roe > 0:
                            health_score += 10

                    if current_ratio and current_ratio != 'False':
                        current_ratio_val = self._parse_value_with_unit(current_ratio)
                        if current_ratio_val > 1.5:
                            health_score += 20
                        elif current_ratio_val > 1:
                            health_score += 10

                    if debt_ratio and debt_ratio != 'False':
                        debt_ratio_val = float(debt_ratio.rstrip('%'))
                        if debt_ratio_val < 50:
                            health_score += 20
                        elif debt_ratio_val < 70:
                            health_score += 10

                    # 计算平均增长率
                    if len(financial_data) > 1:
                        prev_data = financial_data.iloc[-2]
                        prev_revenue = prev_data.get('营业总收入', 0)
                        if prev_revenue and prev_revenue != 'False' and total_revenue and total_revenue != 'False' and self._parse_value_with_unit(prev_revenue) > 0:
                            avg_growth = (self._parse_value_with_unit(total_revenue) - self._parse_value_with_unit(prev_revenue)) / self._parse_value_with_unit(prev_revenue) * 100
            except Exception as e:
                pass  # 忽略数据获取错误

            # 让大模型自主判断投资建议
            result += "请基于财务健康评分和成长数据给出投资建议\n"

            # 8. 数据质量报告
            result += "\n8️⃣ 数据质量报告\n"
            result += "-" * 20 + "\n"
            
            try:
                # 重新获取最新数据用于质量检查
                import akshare as ak
                financial_data = ak.stock_financial_abstract_ths(symbol=stock_code)
                if not financial_data.empty:
                    latest_data = financial_data.iloc[-1].to_dict()
                    
                    # 生成数据质量报告
                    quality_report = data_quality_checker.check_financial_data(
                        latest_data,
                        api_source="同花顺财务摘要(stock_financial_abstract_ths)"
                    )
                    
                    # 添加质量摘要
                    quality_summary = data_quality_checker.generate_quality_summary(quality_report)
                    result += quality_summary + "\n\n"
                    
                    # 添加关键字段的质量标注说明
                    result += "📋 数据来源标识说明：\n"
                    result += "  📡 = API直接返回数据（高质量）\n"
                    result += "  🔢 = 基于原始数据计算（中等质量）\n"
                    result += "  📊 = 估算值（低质量）\n"
                    result += "  ⚠️  = 数据缺失或异常\n"
            except Exception as e:
                result += f"数据质量检查失败: {e}\n"
            
            result += "\n" + "=" * 50 + "\n"
            result += "📅 报告生成时间: " + str(pd.Timestamp.now()) + "\n"
            result += "⚠️  本报告基于公开财务数据，仅供参考\n"

            return result

        except Exception as e:
            return f"综合财务分析失败: {e}"
    async def _analyze_debt_structure(self, stock_code: str) -> str:
        """分析债务结构和偿债能力"""
        try:
            result = f"📊 股票{stock_code}债务结构分析\n\n"
            
            # 获取财务摘要数据
            try:
                import akshare as ak
                financial_data = ak.stock_financial_abstract_ths(symbol=stock_code)
                if financial_data.empty:
                    return f"无法获取股票{stock_code}的财务数据"
            except Exception as e:
                return f"获取财务数据失败: {e}"
            
            # 获取最新一期数据
            latest_data = financial_data.iloc[-1] if len(financial_data) > 0 else financial_data.iloc[0]
            
            # 分析债务规模
            total_liabilities = latest_data.get('负债合计', 0)
            total_assets = latest_data.get('资产总计', 0)
            
            if total_liabilities and total_liabilities != 'False' and total_assets and total_assets != 'False':
                result += "💳 债务规模：\n"
                result += f"  总负债: {self._parse_value_with_unit(total_liabilities):,.0f}万元\n"
                result += f"  总资产: {self._parse_value_with_unit(total_assets):,.0f}万元\n"
                
                # 资产负债率
                debt_ratio_str = latest_data.get('资产负债率', 0)
                if debt_ratio_str and debt_ratio_str != 'False':
                    debt_ratio = float(str(debt_ratio_str).replace('%', ''))
                    result += f"  资产负债率: {debt_ratio:.1f}%\n"
                    
                    # 让大模型自主判断负债水平
                    result += "  请基于资产负债率数据评估负债水平和财务风险\n"
                result += "\n"
            
            # 分析流动性
            current_ratio = latest_data.get('流动比率', 0)
            if current_ratio and current_ratio != 'False':
                current_ratio_val = self._parse_value_with_unit(current_ratio)
                result += "💧 流动性分析：\n"
                result += f"  流动比率: {current_ratio_val:.2f}\n"
                
                # 让大模型自主判断流动性水平
                result += "  请基于流动比率数据评估流动性水平和短期偿债能力\n"
                result += "\n"
            
            # 分析长期偿债能力
            equity = latest_data.get('股东权益合计', 0)
            if equity and equity != 'False' and total_liabilities and total_liabilities != 'False':
                result += "🏦 长期偿债能力：\n"
                equity_ratio = self._parse_value_with_unit(equity) / self._parse_value_with_unit(total_assets) * 100 if self._parse_value_with_unit(total_assets) > 0 else 0
                result += f"  股东权益比率: {equity_ratio:.1f}%\n"
                
                # 让大模型自主判断资本结构
                result += "  请基于股东权益比率数据评估资本结构和抗风险能力\n"
                result += "\n"
            
            # 利息保障倍数（如果有数据）
            operating_profit = latest_data.get('营业利润', 0)
            if operating_profit and operating_profit != 'False':
                result += "💰 盈利对债务的覆盖：\n"
                # 简化计算：用营业利润作为参考
                if '亿' in str(operating_profit):
                    profit_value = float(str(operating_profit).replace('亿', '')) * 10000
                elif '万' in str(operating_profit):
                    profit_value = float(str(operating_profit).replace('万', ''))
                else:
                    profit_value = self._parse_value_with_unit(operating_profit)
                
                result += f"  营业利润: {profit_value:,.0f}万元\n"
                
                # 让大模型自主判断盈利对债务的覆盖能力
                result += "  请基于营业利润数据评估对债务的覆盖能力和偿债能力\n"
            
            return result
            
        except Exception as e:
            return f"债务结构分析失败: {e}"

    async def _analyze_operating_efficiency(self, stock_code: str) -> str:
        """分析运营效率"""
        try:
            result = f"⚡ 股票{stock_code}运营效率分析\n\n"
            
            # 获取财务摘要数据
            try:
                import akshare as ak
                financial_data = ak.stock_financial_abstract_ths(symbol=stock_code)
                if financial_data.empty:
                    return f"无法获取股票{stock_code}的财务数据"
            except Exception as e:
                return f"获取财务数据失败: {e}"
            
            # 获取最新一期数据
            latest_data = financial_data.iloc[-1] if len(financial_data) > 0 else financial_data.iloc[0]
            
            # 分析总资产周转率
            total_revenue = latest_data.get('营业总收入', 0)
            total_assets = latest_data.get('资产总计', 0)
            asset_turnover = 0  # 初始化变量
            revenue_value = 0  # 初始化变量
            
            if total_revenue and total_revenue != 'False' and total_assets and total_assets != 'False':
                result += "🔄 资产周转效率：\n"
                
                # 处理单位
                if '亿' in str(total_revenue):
                    revenue_value = float(str(total_revenue).replace('亿', '')) * 10000
                elif '万' in str(total_revenue):
                    revenue_value = float(str(total_revenue).replace('万', ''))
                else:
                    revenue_value = self._parse_value_with_unit(total_revenue)
                
                asset_turnover = revenue_value / self._parse_value_with_unit(total_assets) if self._parse_value_with_unit(total_assets) > 0 else 0
                result += f"  总资产周转率: {asset_turnover:.2f}次/年\n"
                
                # 让大模型自主判断资产利用效率
                result += "  请基于总资产周转率数据评估资产利用效率\n"
                result += "\n"
            
            # 分析存货周转（如果有数据）
            # 注意：财务摘要可能没有存货数据，这里做简化处理
            result += "📦 存货管理效率：\n"
            result += "  存货周转率: 数据暂缺\n"
            result += "  💡 建议查看详细财务报表获取存货数据\n\n"
            
            # 分析应收账款周转
            result += "💵 应收账款管理：\n"
            result += "  应收账款周转率: 数据暂缺\n"
            result += "  💡 建议查看详细财务报表获取应收账款数据\n\n"
            
            # 分析营业周期
            result += "⏱️ 营业周期效率：\n"
            if total_revenue and total_revenue != 'False':
                # 获取现金流数据来评估营业周期
                operating_cf = latest_data.get('经营活动产生的现金流量净额', 0)
                if operating_cf and operating_cf != 'False':
                    cash_conversion = self._parse_value_with_unit(operating_cf) / revenue_value if revenue_value > 0 else 0
                    result += f"  现金转化率: {cash_conversion:.1%}\n"
                    
                    # 让大模型自主判断现金回收效率
                    result += "  请基于现金转化率数据评估现金回收效率\n"
                else:
                    result += "  现金转化率: 数据暂缺\n"
            
            result += "\n"
            
            # 综合运营效率评估
            result += "🎯 运营效率综合评估：\n"
            
            efficiency_score = 0
            if asset_turnover > 1.0:
                efficiency_score += 40
            elif asset_turnover > 0.5:
                efficiency_score += 20
            
            # 检查现金流数据
            operating_cf = latest_data.get('经营活动产生的现金流量净额', 0)
            if operating_cf and operating_cf != 'False' and total_revenue and total_revenue != 'False':
                cash_conv = self._parse_value_with_unit(operating_cf) / revenue_value if revenue_value > 0 else 0
                if cash_conv > 0.5:
                    efficiency_score += 40
                elif cash_conv > 0.3:
                    efficiency_score += 20
            
            # 让大模型自主判断运营效率综合水平
            result += "  请基于综合效率评分评估运营效率水平\n"
            
            return result
            
        except Exception as e:
            return f"运营效率分析失败: {e}"



    async def generate_financial_charts(self, stock_code: str) -> Dict[str, Any]:
        """生成财务分析可视化图表"""
        try:
            self.logger.info(f"开始生成股票{stock_code}的财务分析图表")
            
            # 获取财务数据
            import akshare as ak
            financial_data = ak.stock_financial_abstract_ths(symbol=stock_code)
            
            if financial_data.empty:
                self.logger.warning(f"股票{stock_code}的财务数据不足")
                return {"error": "财务数据不足"}
            
            charts = {}
            
            # 生成财务比率雷达图
            ratios_chart = await self._generate_financial_ratios_radar(financial_data, stock_code)
            if ratios_chart:
                charts["financial_ratios_radar"] = ratios_chart
            
            # 生成财务趋势图
            trend_chart = await self._generate_financial_trend_chart(financial_data, stock_code)
            if trend_chart:
                charts["financial_trend"] = trend_chart
            
            # 生成财务结构分析图
            structure_chart = await self._generate_financial_structure_chart(financial_data, stock_code)
            if structure_chart:
                charts["financial_structure"] = structure_chart
            
            self.logger.info(f"成功生成股票{stock_code}的{len(charts)}个财务分析图表")
            return charts
            
        except Exception as e:
            self.logger.error(f"生成财务分析图表失败: {e}")
            return {"error": f"生成财务分析图表失败: {e}"}
    
    async def _generate_financial_ratios_radar(self, financial_data: pd.DataFrame, stock_code: str) -> Any:
        """生成财务比率雷达图"""
        try:
            if financial_data.empty:
                return None
            
            latest_data = financial_data.iloc[-1] if len(financial_data) > 0 else financial_data.iloc[0]
            
            # 提取财务比率数据
            ratios = {}
            
            # ROE
            net_profit = latest_data.get('净利润', 0)
            equity = latest_data.get('股东权益合计', 0)
            if equity and equity != 'False' and net_profit and net_profit != 'False':
                roe = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(equity) * 100
                ratios['roe'] = min(roe, 50)  # 限制最大值
            
            # 资产负债率
            debt_ratio = latest_data.get('资产负债率', 0)
            if debt_ratio and debt_ratio != 'False':
                debt_ratio_val = float(str(debt_ratio).replace('%', ''))
                ratios['debt_ratio'] = debt_ratio_val
            
            # 净利率
            total_revenue = latest_data.get('营业总收入', 0)
            if total_revenue and total_revenue != 'False' and net_profit and net_profit != 'False':
                net_margin = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(total_revenue) * 100
                ratios['net_margin'] = min(net_margin, 30)  # 限制最大值
            
            # 资产周转率
            total_assets = latest_data.get('资产总计', 0)
            if total_revenue and total_revenue != 'False' and total_assets and total_assets != 'False':
                asset_turnover = self._parse_value_with_unit(total_revenue) / self._parse_value_with_unit(total_assets)
                ratios['asset_turnover'] = min(asset_turnover * 100, 200)  # 转换为百分比并限制
            
            # 流动比率
            current_ratio = latest_data.get('流动比率', 0)
            if current_ratio and current_ratio != 'False':
                current_ratio_val = self._parse_value_with_unit(current_ratio)
                ratios['current_ratio'] = min(current_ratio_val * 20, 100)  # 转换为百分比并限制
            
            if not ratios:
                return None
            
            # 返回图表数据字典，不调用visualizer
            return {
                'type': 'financial_ratios_radar',
                'stock_code': stock_code,
                'title': f"{stock_code} 财务比率雷达图",
                'data': ratios
            }
            
        except Exception as e:
            self.logger.error(f"生成财务比率雷达图失败: {e}")
            return None
    
    async def _generate_financial_trend_chart(self, financial_data: pd.DataFrame, stock_code: str) -> Any:
        """生成财务趋势图"""
        try:
            if financial_data.empty or len(financial_data) < 2:
                return None
            
            # 提取历史财务数据
            dates = []
            revenues = []
            profits = []
            
            for i in range(min(5, len(financial_data))):
                data = financial_data.iloc[-1-i]
                dates.append(f"第{i+1}期")
                
                # 营业收入
                revenue = data.get('营业总收入', 0)
                if revenue and revenue != 'False':
                    revenues.append(self._parse_value_with_unit(revenue))
                else:
                    revenues.append(0)
                
                # 净利润
                profit = data.get('净利润', 0)
                if profit and profit != 'False':
                    profits.append(self._parse_value_with_unit(profit))
                else:
                    profits.append(0)
            
            # 反转数据，使时间顺序正确
            dates.reverse()
            revenues.reverse()
            profits.reverse()
            
            # 创建趋势数据DataFrame
            trend_data = pd.DataFrame({
                '日期': dates,
                '营业收入': revenues,
                '净利润': profits
            })
            
            # 返回图表数据字典，不调用visualizer
            return {
                'type': 'financial_trend',
                'stock_code': stock_code,
                'title': f"{stock_code} 财务趋势图",
                'data': [
                    {
                        'x': dates,
                        'y': revenues,
                        'name': '营业收入',
                        'color': '#1f77b4'
                    },
                    {
                        'x': dates,
                        'y': profits,
                        'name': '净利润',
                        'color': '#ff7f0e'
                    }
                ],
                'chart_type': 'line',
                'x_label': '期间',
                'y_label': '金额(万元)'
            }
            
        except Exception as e:
            self.logger.error(f"生成财务趋势图失败: {e}")
            return None
    
    async def _generate_financial_structure_chart(self, financial_data: pd.DataFrame, stock_code: str) -> Any:
        """生成财务结构分析图"""
        try:
            if financial_data.empty:
                return None
            
            latest_data = financial_data.iloc[-1] if len(financial_data) > 0 else financial_data.iloc[0]
            
            # 提取资产结构数据
            total_assets = latest_data.get('资产总计', 0)
            total_liabilities = latest_data.get('负债合计', 0)
            equity = latest_data.get('股东权益合计', 0)
            
            if not total_assets or total_assets == 'False':
                return None
            
            # 计算各项占比
            assets_value = self._parse_value_with_unit(total_assets)
            liabilities_value = self._parse_value_with_unit(total_liabilities) if total_liabilities and total_liabilities != 'False' else 0
            equity_value = self._parse_value_with_unit(equity) if equity and equity != 'False' else 0
            
            # 创建结构分析数据
            structure_data = {
                'labels': ['总资产', '总负债', '股东权益'],
                'values': [assets_value, liabilities_value, equity_value]
            }
            
            # 返回图表数据字典，不调用visualizer
            return {
                'type': 'financial_structure',
                'stock_code': stock_code,
                'title': f"{stock_code} 财务结构分析",
                'data': structure_data,
                'chart_type': 'pie'
            }
            
        except Exception as e:
            self.logger.error(f"生成财务结构分析图失败: {e}")
            return None

    async def _generate_fundamental_signals(self, stock_code: str, output_format: str = "text") -> Union[str, Dict]:
        """
        生成财务面信号分析，支持文本和JSON格式输出
        
        Args:
            stock_code: 股票代码
            output_format: 输出格式，"text"或"json"
            
        Returns:
            文本分析结果或JSON格式的财务分析数据
        """
        try:
            # 获取财务数据
            import akshare as ak
            financial_data = ak.stock_financial_abstract_ths(symbol=stock_code)
            if financial_data.empty:
                return {"error": "无法获取财务数据"} if output_format == "json" else "无法获取股票财务数据"
            
            latest_data = financial_data.iloc[-1] if len(financial_data) > 0 else financial_data.iloc[0]
            
            if output_format == "json":
                # JSON格式输出
                score = await self._calculate_fundamental_score(latest_data)
                confidence = await self._calculate_fundamental_confidence(latest_data)
                analysis = await self._analyze_fundamental_metrics(latest_data)
                summary = await self._generate_fundamental_summary(latest_data)
                
                return {
                    "dimension": "fundamental",
                    "score": score,
                    "analysis": {
                        **analysis,
                        "summary": summary
                    },
                    "confidence": confidence,
                    "timestamp": datetime.utcnow().isoformat() + "Z"
                }
            else:
                # 文本格式输出（保持向后兼容）
                result = f"📊 股票{stock_code}财务面信号分析\n\n"
                
                # 计算评分
                score = await self._calculate_fundamental_score(latest_data)
                result += f"⭐ 财务面评分: {score}/10\n\n"
                
                # 添加详细分析
                result += await self._comprehensive_financial_analysis(stock_code)
                
                return result
                
        except Exception as e:
            error_msg = f"财务面信号分析失败: {e}"
            return {"error": error_msg} if output_format == "json" else error_msg

    async def _calculate_fundamental_score(self, financial_data: pd.Series) -> float:
        """
        使用大模型计算0-10分的财务面评分
        
        Args:
            financial_data: 财务数据Series
            
        Returns:
            0-10分的评分
        """
        try:
            # 构建财务分析数据
            analysis_data = await self._prepare_fundamental_analysis_data(financial_data)
            
            # 使用大模型进行评分
            scoring_prompt = self._get_fundamental_scoring_prompt(analysis_data)
            llm_response = await self.llm.ainvoke(scoring_prompt)
            
            # 解析大模型响应
            scoring_result = self._parse_llm_scoring_response(llm_response)
            
            # 验证并限制评分范围
            score = self._validate_and_clamp_score(scoring_result.get('score', 5))
            
            self.logger.info(f"基本面分析大模型评分结果: {score}/10")
            return score
            
        except Exception as e:
            self.logger.error(f"财务面评分计算失败: {e}")
            return 5.0  # 默认中等评分

    async def _prepare_fundamental_analysis_data(self, financial_data: pd.Series) -> Dict[str, Any]:
        """
        准备基本面分析数据供大模型使用
        
        Args:
            financial_data: 财务数据Series
            
        Returns:
            结构化的基本面分析数据
        """
        try:
            analysis_data = {
                "profitability": {},
                "solvency": {},
                "efficiency": {},
                "growth": {},
                "cash_flow": {}
            }
            
            # 盈利能力指标
            net_profit = financial_data.get('净利润', 0)
            total_revenue = financial_data.get('营业总收入', 0)
            equity = financial_data.get('股东权益合计', 0)
            total_assets = financial_data.get('资产总计', 0)
            
            if equity and equity != 'False' and net_profit and net_profit != 'False':
                roe = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(equity) * 100
                analysis_data["profitability"]["roe"] = roe
            
            if total_assets and total_assets != 'False' and net_profit and net_profit != 'False':
                roa = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(total_assets) * 100
                analysis_data["profitability"]["roa"] = roa
            
            if total_revenue and total_revenue != 'False' and net_profit and net_profit != 'False':
                net_margin = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(total_revenue) * 100
                analysis_data["profitability"]["net_margin"] = net_margin
            
            # 偿债能力指标
            debt_ratio = financial_data.get('资产负债率', 0)
            current_ratio = financial_data.get('流动比率', 0)
            
            if debt_ratio and debt_ratio != 'False':
                analysis_data["solvency"]["debt_ratio"] = float(str(debt_ratio).replace('%', ''))
            
            if current_ratio and current_ratio != 'False':
                analysis_data["solvency"]["current_ratio"] = self._parse_value_with_unit(current_ratio)
            
            # 运营效率指标
            if total_revenue and total_revenue != 'False' and total_assets and total_assets != 'False':
                asset_turnover = self._parse_value_with_unit(total_revenue) / self._parse_value_with_unit(total_assets)
                analysis_data["efficiency"]["asset_turnover"] = asset_turnover
            
            # 现金流指标
            operating_cf = financial_data.get('经营活动产生的现金流量净额', 0)
            if operating_cf and operating_cf != 'False':
                analysis_data["cash_flow"]["operating_cash_flow"] = self._parse_value_with_unit(operating_cf)
            
            # 成长性指标（如果有历史数据）
            # 这里简化处理，实际应用中可以从历史数据计算增长率
            
            return analysis_data
            
        except Exception as e:
            self.logger.error(f"准备基本面分析数据失败: {e}")
            return {}

    def _get_fundamental_scoring_prompt(self, analysis_data: Dict[str, Any]) -> str:
        """
        构建基本面分析的大模型评分prompt
        
        Args:
            analysis_data: 基本面分析数据
            
        Returns:
            评分prompt字符串
        """
        prompt = f"""
        你是一个专业的财务分析师，请基于以下财务数据对公司的基本面进行评分。

        财务分析数据：
        {analysis_data}

        评分标准（0-10分整数）：
        - 10分：财务状况完美，盈利优秀，偿债能力强，运营效率高，现金流充裕
        - 8-9分：财务状况优秀，各项指标健康，具备较强竞争力
        - 6-7分：财务状况良好，基本满足投资要求，存在个别可改进项
        - 4-5分：财务状况一般，存在一定财务风险，需要关注
        - 2-3分：财务状况较差，多项指标不佳，投资风险较高
        - 0-1分：财务状况极差，存在重大财务问题，不建议投资

        请综合考虑以下维度：
        1. 盈利能力：ROE、ROA、净利率等指标
        2. 偿债能力：资产负债率、流动比率等指标
        3. 运营效率：资产周转率等指标
        4. 现金流状况：经营现金流等指标
        5. 财务健康度：各项指标的协调性和稳定性

        请严格按照以下JSON格式输出：
        {{
            "score": 0-10之间的整数,
            "reasoning": "详细的评分理由，包括各维度的分析",
            "strengths": ["财务优势1", "财务优势2", ...],
            "weaknesses": ["财务劣势1", "财务劣势2", ...]
        }}

        请确保评分是0-10之间的整数，并给出充分的评分理由。
        """
        return prompt

    def _parse_llm_scoring_response(self, llm_response: Any) -> Dict[str, Any]:
        """
        解析大模型评分响应
        
        Args:
            llm_response: 大模型响应
            
        Returns:
            解析后的评分结果
        """
        try:
            import json
            import re
            
            response_text = str(llm_response)
            
            # 尝试提取JSON格式内容
            json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
            if json_match:
                json_str = json_match.group()
                scoring_result = json.loads(json_str)
                
                # 验证必需字段
                if 'score' in scoring_result:
                    return scoring_result
            
            # 如果JSON解析失败，尝试从文本中提取评分
            score_match = re.search(r'"score"\s*:\s*(\d+)', response_text)
            if score_match:
                score = int(score_match.group(1))
                return {
                    "score": score,
                    "reasoning": "从响应中提取的评分",
                    "strengths": [],
                    "weaknesses": []
                }
            
            # 如果都失败，返回默认值
            self.logger.warning("无法解析大模型评分响应，使用默认评分")
            return {
                "score": 5,
                "reasoning": "解析失败，使用默认评分",
                "strengths": [],
                "weaknesses": []
            }
            
        except Exception as e:
            self.logger.error(f"解析大模型评分响应失败: {e}")
            return {
                "score": 5,
                "reasoning": f"解析失败: {e}",
                "strengths": [],
                "weaknesses": []
            }

    def _validate_and_clamp_score(self, score: Union[int, float]) -> int:
        """
        验证并限制评分范围在0-10之间
        
        Args:
            score: 原始评分
            
        Returns:
            验证后的整数评分 (0-10)
        """
        try:
            # 转换为整数
            if isinstance(score, (int, float)):
                clamped_score = max(0, min(10, int(round(score))))
                return clamped_score
            else:
                self.logger.warning(f"评分类型无效: {type(score)}，使用默认评分5")
                return 5
        except Exception as e:
            self.logger.error(f"评分验证失败: {e}")
            return 5


    async def _calculate_fundamental_confidence(self, financial_data: pd.Series) -> float:
        """
        计算分析置信度
        
        Args:
            financial_data: 财务数据Series
            
        Returns:
            置信度 (0-1之间)
        """
        try:
            confidence = 0.8  # 基础置信度
            
            # 检查数据完整性
            required_fields = ['净利润', '营业总收入', '股东权益合计', '资产总计']
            available_fields = 0
            
            for field in required_fields:
                if field in financial_data and financial_data[field] and financial_data[field] != 'False':
                    available_fields += 1
            
            # 数据完整性影响置信度
            data_completeness = available_fields / len(required_fields)
            confidence *= data_completeness
            
            # 检查数据质量（简化处理）
            net_profit = financial_data.get('净利润', 0)
            if net_profit and net_profit != 'False':
                profit_value = self._parse_value_with_unit(net_profit)
                if profit_value <= 0:  # 亏损可能影响数据质量
                    confidence *= 0.9
            
            return max(0.1, min(1.0, confidence))
            
        except Exception as e:
            self.logger.error(f"置信度计算失败: {e}")
            return 0.5

    async def _analyze_fundamental_metrics(self, financial_data: pd.Series) -> Dict:
        """
        分析财务指标，返回结构化数据
        
        Args:
            financial_data: 财务数据Series
            
        Returns:
            包含各项财务指标的结构化数据
        """
        try:
            analysis = {
                "profitability": {},
                "solvency": {},
                "efficiency": {},
                "health_score": 0
            }
            
            # 盈利能力指标
            net_profit = financial_data.get('净利润', 0)
            total_revenue = financial_data.get('营业总收入', 0)
            equity = financial_data.get('股东权益合计', 0)
            total_assets = financial_data.get('资产总计', 0)
            
            if equity and equity != 'False' and net_profit and net_profit != 'False':
                analysis["profitability"]["roe"] = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(equity) * 100
            
            if total_assets and total_assets != 'False' and net_profit and net_profit != 'False':
                analysis["profitability"]["roa"] = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(total_assets) * 100
            
            if total_revenue and total_revenue != 'False' and net_profit and net_profit != 'False':
                analysis["profitability"]["net_margin"] = self._parse_value_with_unit(net_profit) / self._parse_value_with_unit(total_revenue) * 100
            
            # 偿债能力指标
            debt_ratio = financial_data.get('资产负债率', 0)
            current_ratio = financial_data.get('流动比率', 0)
            
            if debt_ratio and debt_ratio != 'False':
                analysis["solvency"]["debt_ratio"] = float(str(debt_ratio).replace('%', ''))
            
            if current_ratio and current_ratio != 'False':
                analysis["solvency"]["current_ratio"] = self._parse_value_with_unit(current_ratio)
            
            # 运营效率指标
            if total_revenue and total_revenue != 'False' and total_assets and total_assets != 'False':
                analysis["efficiency"]["asset_turnover"] = self._parse_value_with_unit(total_revenue) / self._parse_value_with_unit(total_assets)
            
            # 财务健康度评分 - 使用大模型综合评分
            fundamental_score = await self._calculate_fundamental_score(financial_data)
            analysis["health_score"] = fundamental_score * 10  # 转换为0-100分
            
            return analysis
            
        except Exception as e:
            self.logger.error(f"财务指标分析失败: {e}")
            return {
                "profitability": {},
                "solvency": {},
                "efficiency": {},
                "health_score": 50
            }

    async def _generate_fundamental_summary(self, financial_data: pd.Series) -> str:
        """
        生成财务分析摘要
        
        Args:
            financial_data: 财务数据Series
            
        Returns:
            文本摘要
        """
        try:
            score = await self._calculate_fundamental_score(financial_data)
            
            if score >= 8:
                return "财务状况优秀，盈利能力和偿债能力极强"
            elif score >= 6:
                return "财务状况良好，主要财务指标表现稳健"
            elif score >= 4:
                return "财务状况一般，存在一定财务风险需要关注"
            elif score >= 2:
                return "财务状况较弱，多项指标表现不佳"
            else:
                return "财务状况极差，存在重大财务风险"
                
        except Exception as e:
            self.logger.error(f"摘要生成失败: {e}")
            return "财务分析摘要生成失败"


# 全局实例
stock_fundamental_analysis_agent = StockFundamentalAnalysisAgent()